package kvraft

import (
	"crypto/rand"
	"math/big"
	"sync"

	"../labrpc"
)

type Clerk struct {
	servers []*labrpc.ClientEnd
	// You will have to modify this struct.

	mu         sync.Mutex
	ID         int64
	reqNum     int
	lastleader int
}

func nrand() int64 {
	max := big.NewInt(int64(1) << 62)
	bigx, _ := rand.Int(rand.Reader, max)
	x := bigx.Int64()
	return x
}

func MakeClerk(servers []*labrpc.ClientEnd) *Clerk {
	ck := new(Clerk)
	ck.servers = servers
	// You'll have to add code here.
	ck.ID = nrand()
	ck.reqNum = 0
	ck.lastleader = 0
	return ck
}

//
// fetch the current value for a key.
// returns "" if the key does not exist.
// keeps trying forever in the face of all other errors.
//
// you can send an RPC with code like this:
// ok := ck.servers[i].Call("KVServer.Get", &args, &reply)
//
// the types of args and reply (including whether they are pointers)
// must match the declared types of the RPC handler function's
// arguments. and reply must be passed as a pointer.
//
func (ck *Clerk) Get(key string) string {
	// You will have to modify this function.
	args := GetArgs{}
	reply := GetReply{}
	ck.mu.Lock()
	args.Key = key
	args.ClientID = ck.ID
	args.ReqNum = ck.reqNum
	ck.reqNum++
	ck.mu.Unlock()
	var value string
	succeed := false
	ok := ck.servers[ck.lastleader].Call("KVServer.Get", &args, &reply)
	if ok {
		if reply.Err == OK || reply.Err == ErrNoKey {
			succeed = true
			value = reply.Value
		}
	}
	for !succeed {
		for i := 0; i < len(ck.servers); i++ {
			ok := ck.servers[i].Call("KVServer.Get", &args, &reply)
			if ok {
				if reply.Err == OK || reply.Err == ErrNoKey {
					succeed = true
					ck.lastleader = i
					value = reply.Value
					break
				}
			}
		}
	}
	return value
}

//
// shared by Put and Append.
//
// you can send an RPC with code like this:
// ok := ck.servers[i].Call("KVServer.PutAppend", &args, &reply)
//
// the types of args and reply (including whether they are pointers)
// must match the declared types of the RPC handler function's
// arguments. and reply must be passed as a pointer.
//
func (ck *Clerk) PutAppend(key string, value string, op string) {
	// You will have to modify this function.
	args := PutAppendArgs{}
	reply := PutAppendReply{}
	ck.mu.Lock()
	args.Key = key
	args.Op = op
	args.Value = value
	args.ClientID = ck.ID
	args.ReqNum = ck.reqNum
	ck.reqNum++
	ck.mu.Unlock()
	succeed := false
	ck.servers[ck.lastleader].Call("KVServer.PutAppend", &args, &reply)
	if reply.Err == OK {
		succeed = true
		//DPrintf("clinet putappend {%v, %v}", key, value)
	}
	for !succeed {
		for i := 0; i < len(ck.servers); i++ {
			ck.servers[i].Call("KVServer.PutAppend", &args, &reply)
			if reply.Err == OK {
				succeed = true
				ck.lastleader = i
				//DPrintf("clinet putappend {%v, %v}", key, value)
				break
			}
			//DPrintf("clinet putappend {%v, %v}", key, value)
		}
	}
}

func (ck *Clerk) Put(key string, value string) {
	ck.PutAppend(key, value, "Put")
}
func (ck *Clerk) Append(key string, value string) {
	ck.PutAppend(key, value, "Append")
}
